package com.visionet.waveletData.web.common.utils;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.*;
import com.visionet.waveletData.web.common.utilities.props.PropsKeys;
import com.visionet.waveletData.web.common.utilities.props.PropsUtil;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class OssBackup {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	private static OSSClient client;
	private static String bucketName;
	private static String endpoint = PropsUtil.getProperty(PropsKeys.UPLOAD_FILE_ENDPOINT);
	private static String key = PropsUtil.getProperty(PropsKeys.UPLOAD_FILE_KEY);
	private static String secret = PropsUtil.getProperty(PropsKeys.UPLOAD_FILE_SECRET);
	private static String name = PropsUtil.getProperty(PropsKeys.UPLOAD_FILE_NAME);
	static {
		client = new OSSClient(endpoint, key, secret);
		bucketName = name;
	}

	/**
	 * Upload file
	 *
	 */
	public void putObject(InputStream content, String remotePath, String filename, long filelength) {
		// 获取指定文件的输入流
		try {
			// 创建上传Object的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			// 必须设置ContentLength
			meta.setContentLength(filelength);
			//meta.setCacheControl("no-cache");
			//meta.setContentEncoding("utf-8");
			//meta.setContentDisposition("attachment;filename="+filename);
			//meta.setContentType("image/jpg");
			client.putObject(bucketName, remotePath+"/"+filename, content, meta);
		} catch (Exception e) {
			logger.error("上传图片到OSS失败", e);
			throw new RuntimeException("上传图片到OSS失败", e);
		}
	}

	public void deleteRemoteObject(String remote) {
		// 删除Object
		client.deleteObject(bucketName, remote);
	}

	public void deleteRemoteFolder(String remote) {
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		// 递归列出"directory"目录下的所有文件
		listObjectsRequest.setPrefix(remote);
		// List Objects
		ObjectListing listing = client.listObjects(listObjectsRequest);
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			deleteRemoteObject(objectSummary.getKey());
		}
	}

	public void deleteLocalFolder(String local) {
		File file = new File(local);
		try {
			if (file.isDirectory()) {
				FileUtils.deleteDirectory(new File(local));
			} else {
				FileUtils.forceDelete(file);
			}
		} catch (IOException e) {
			logger.error("Delete local file [{}] due to error", local);
		}
	}

	public InputStream getObject(String fileRemotePath) {
		logger.debug("File path: "+fileRemotePath);
		GetObjectRequest request = new GetObjectRequest(Constants.get("oss.bucket.name"), fileRemotePath);
		OSSObject object = client.getObject(request);
		InputStream input = object.getObjectContent();
		return input;
	}
}
